package com.chukun.gateway.core.filter.impl;

import com.chukun.gateway.core.context.GatewayContext;
import com.chukun.gateway.core.filter.Filter;
import com.chukun.gateway.core.filter.annotation.FilterDefinition;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.impl.DefaultClaims;
import lombok.extern.slf4j.Slf4j;

import static com.chukun.gateway.common.constants.GlobalFilterConst.*;

/**
 * @author chukun
 * @version 1.0.0
 * @description 用户鉴权,登录服务里面一般会写入鉴权的秘钥，这个filter只做权限的校验
 * @createTime 2023/12/18 23:06
 */
@Slf4j
@FilterDefinition(id= USER_AUTH_FILTER_ID, name = USER_AUTH_FILTER_NAME, order =USER_AUTH_FILTER_ORDER )
public class UserAuthFilter implements Filter {

    private static final String SECRET_KEY = "api-gateway-user-auth-filter";
    private static final String COOKIE_NAME = "user-jwt";

    @Override
    public void doFilter(GatewayContext ctx) throws Exception {
        //检查是否需要用户鉴权
//        if (ctx.getRule().getFilterConfig(USER_AUTH_FILTER_ID) == null) {
//            return;
//        }
//        String token = ctx.getRequest().getCookie(COOKIE_NAME).value();
//        if (StringUtils.isBlank(token)) {
//            throw new ResponseException(ResponseCode.UNAUTHORIZED);
//        }
//        try {
//            //解析用户id
//            long userId = parseUserId(token);
//            //把用户id传给下游
//            ctx.getRequest().setUserId(userId);
//        } catch (Exception e) {
//            throw new ResponseException(ResponseCode.UNAUTHORIZED);
//        }
    }

    private long parseUserId(String token) {
        Jwt jwt = Jwts.parser().setSigningKey(SECRET_KEY).parse(token);
        return Long.parseLong(((DefaultClaims)jwt.getBody()).getSubject());
    }
}
